/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.security;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.UserService;

/**
 * MyAuthenticationFailureHandler.java
 * 
 * @author Administrator
 */
@Component
public class MyAuthenticationFailureHandler
		extends
			SimpleUrlAuthenticationFailureHandler {
	@Resource
	private UserService userService;
	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		@SuppressWarnings("deprecation")
		CoreUser coreUser = userService.findById(exception.getAuthentication()
				.getPrincipal().toString());
		if (coreUser == null) {
			exception = new BadCredentialsException("用户不存在！");
			setDefaultFailureUrl("/login?errorType=3");
		} else if (coreUser.getLogincount() < CommonParamter.ERROR_MAX_TIMES) {
			// 正常状态
			int errorTimes = coreUser.getLogincount() + 1;
			if (errorTimes >= CommonParamter.ERROR_MAX_TIMES) {
				coreUser.setLoginexpire(new Date());
				exception = new BadCredentialsException("账户出错次数已达最大值！",
						exception.getCause());
				setDefaultFailureUrl("/login?errorType=2");
			} else {
				setDefaultFailureUrl("/login?errorType=1");
				exception = new BadCredentialsException("密码错误，还有"
						+ (CommonParamter.ERROR_MAX_TIMES - errorTimes)
						+ "次机会！", exception.getCause());
			}
			coreUser.setLogincount((byte) errorTimes);
			userService.update(coreUser);
		} else {
			// 账户被锁定
			// do nothing
		}
		super.onAuthenticationFailure(request, response, exception);

	}
}
